package com.shanghaionstar.carmanage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.PackageType;
import com.onstar.cn.more.entity.FlowDataComplexType;
import com.onstar.cn.more.response.DataPackageEntity;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.adapter.PackageFlowAdapter;
import com.shanghaionstar.carmanage.iview.ICarFlowDataView;
import com.shanghaionstar.carmanage.presenter.CarFlowDataPresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.weight.CommonNoDatasLayout;
import com.shanghaionstar.weight.TopLayout;

import java.math.BigDecimal;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 4G套餐页面：
 *
 * Created by Yonglang Hong on 2016/7/25.
 */
public class CarManager4GFragment extends BaseFragment implements ICarFlowDataView,View.OnClickListener{

    @FindViewById
    private TopLayout top_layout;

    /*******加载动画********/
    @FindViewById
    private ProgressLayout pl_loading;

    /*******数据显示区域********/
    @FindViewById
    private View  ll_dataArea,rcbtn_buyMore;
    /*******总流量/单位********/
    @FindViewById
    private TextView tv_sumFlow,tv_flowUnit,tv_flowCaculator;
    /*******服务列表********/
    @FindViewById
    private ListView lsv_service;

    /*******无列表数据布局********/
    @FindViewById
    private CommonNoDatasLayout cndl_noDatas;
    /*******请求异常布局********/
    @FindViewById
    private CommonNoDatasLayout cndl_err;

    /*******流量业务代理********/
    private CarFlowDataPresenter mPresenter;

    /******是否已经成功加载过*****/
    boolean hasLoading;

    @Override
    public int getLayoutId() {
        return R.layout.car_manage_fragment_4g;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !hasLoading){
            showTopLayout(false);
            init();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint() && !hasLoading){
            showTopLayout(true);
            init();
        }
    }

    /**
     * 显示导航栏（为了在“我的”页面中的流量套餐复用CarManager4GFragment）
     * @param isShow
     */
    private void showTopLayout(boolean isShow){
        top_layout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        if (isShow)
            top_layout.setOnRightTextClickLstener(getString(R.string.order_record_tittle), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BusinessUtil.sendReportByClickType(getContext(), FunctionNameFindId.ButlerWIFIOrderHistory.getStringValue());
                    Intent intent = new Intent(baseActivity, OrderRecordActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(OrderRecordActivity.PACKAGE_TYPE, PackageType.DATA);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
    }

    private void init(){
        loadFlowDatas();
        registerOrderPaySuccess();
    }

    private Subscription mPaySuccessRx;

    /**
     * 购买套餐成功后刷新页面
     */
    private void registerOrderPaySuccess(){
        mPaySuccessRx = RxBus.getDefault().toObserverable(OrderPayActivity.PAY_SUCCESS, Integer.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer resp) {
                        loadFlowDatas();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
        RxSubscriptions.add(mPaySuccessRx);
    }

    @OnClick({R.id.rcbtn_buyMore,R.id.tv_flowCaculator})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rcbtn_buyMore:
                BusinessUtil.sendReportByClickType(getContext(), FunctionNameFindId.BuyMoreDataPackage_4G.getStringValue());
                Intent payMeIntent = new Intent(getActivity(), FlowPackageActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("packageType", PackageType.DATA);
                payMeIntent.putExtras(bundle);
                startActivity(payMeIntent);
                break;
            case R.id.tv_flowCaculator:
                BusinessUtil.sendReportByClickType(getContext(), FunctionNameFindId.DataCaculator_4G.getStringValue());
                startActivity(new Intent(baseActivity,FlowCalCulationActivity.class));
                break;
        }
    }

    public CarFlowDataPresenter getmPresenter() {
        return mPresenter == null ? new CarFlowDataPresenter(baseActivity.getScheduler(),baseActivity,this):mPresenter;
    }

    /**
     * 异步加载流量数据
     */
    private void loadFlowDatas(){
        hasLoading = true;
        pl_loading.setVisibility(View.VISIBLE);
        getmPresenter().getFlowData();
    }

    @Override
    public void showFlowData(DataPackageEntity flowData) {
        //显示数据布局，隐藏加载动画、异常布局
        pl_loading.setVisibility(View.GONE);
        cndl_err.setVisibility(View.GONE);
        ll_dataArea.setVisibility(View.VISIBLE);
        //显示流量套餐信息
        showFlowInfo(flowData.getCurrentRemainUsage(),
                flowData.getCurrRemainUsageUnit(),
                flowData.getTotalRemainUsage(),
                flowData.getTotalRemainUsageUnit());
        //显示套餐列表
        showPackageList(flowData.getPackageUsageInfos());
    }

    private void showPackageList(List<FlowDataComplexType> packageDateList){
        if (packageDateList == null || packageDateList.isEmpty()) {
            lsv_service.setVisibility(View.GONE);
            cndl_noDatas.setVisibility(View.VISIBLE);
            cndl_err.showIcon(true);
            cndl_noDatas.setRefreshImage(R.drawable.no_datas);
        }else {
            lsv_service.setVisibility(View.VISIBLE);
            cndl_noDatas.setVisibility(View.GONE);
            lsv_service.setAdapter(new PackageFlowAdapter(packageDateList,baseActivity));
            setOnItemClick();
        }
    }

    private void setOnItemClick(){
        lsv_service.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
    }

    @Override
    public void showErrorGetmsg(boolean isShow,Throwable throwable) {
        //出错则重新加载
        hasLoading = false;
        //显示异常布局
        pl_loading.setVisibility(View.GONE);
        ll_dataArea.setVisibility(View.GONE);
        cndl_err.setVisibility(isShow ? View.VISIBLE : View.GONE);
        cndl_err.showIcon(true);
        cndl_err.setHintText(R.string.no_payme_list_datas_error);
        cndl_err.setOnRefreshListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFlowDatas();
            }
        });
        if (throwable instanceof OnStarException)
            AlertDialogUtil.showDialogByOnstarException(baseActivity, (OnStarException)throwable);
    }

    @Override
    public void showNoDataMsg(boolean isShow) {
        //显示异常布局
        pl_loading.setVisibility(View.GONE);
        ll_dataArea.setVisibility(View.GONE);
        cndl_err.setVisibility(isShow ? View.VISIBLE : View.GONE);
        cndl_err.setHintText("没有查询到相关信息");
    }

    /**
     * 显示流量信息
     */
    private void showFlowInfo(String curRemain, String curUnit,String total, String totalUnit) {
        //总流量显示
        BigDecimal totalFlowData = new BigDecimal(curRemain);
        if(Double.parseDouble(curRemain) <= 0){
            tv_sumFlow.setText("0");
            tv_flowUnit.setText(curUnit);
        }else{
            tv_sumFlow.setText(totalFlowData.setScale(1, BigDecimal.ROUND_HALF_UP).toString());
            tv_flowUnit.setText(curUnit);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mPaySuccessRx);
        release();
    }

    private void release(){
        if (mPresenter != null) {
            mPresenter.finish();
            mPresenter = null;
        }
    }

    /************no use**********/
    @Override
    public void setLoading(boolean isLoading) {
    }
    @Override
    public void onResponseError(OnStarException e) {
    }
    @Override
    public void onReponseSuccess(Object object) {
    }
    @Override
    public Activity onActivity() {
        return null;
    }
    /************no use**********/
}
